package com.example.makerspace.dao;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Data
public abstract class BaseDAO<T>{
    protected BaseMapper<T> mapper;

    public T selectById(int id){
        return mapper.selectById(id);
    }

    public boolean insert(T t){
        int insert = mapper.insert(t);
        return insert == 1;
    }

    public boolean updateById(T t){
        int i = mapper.updateById(t);
        return i == 1;
    }

    public boolean deleteById(int id){
        int i = mapper.deleteById(id);
        return i == 1;
    }

    public List<T> selectAll(){
        return mapper.selectList(null);
    }

    public List<T> selectByIds(List<Integer> ids) {
        return mapper.selectBatchIds(ids);
    }

    public IPage<T> page(Page<T> queryPage, Map<?, ?> selectParam) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
        Optional.ofNullable(selectParam).ifPresent(map -> {
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                key = StringUtils.camelToUnderline(key);
                queryWrapper.eq(key, value);
            }
        });
        queryWrapper.orderByDesc("create_time");
        return mapper.selectPage(queryPage, queryWrapper);
    }

    public List<T> distinctValue(String filedName){
        return mapper.selectList(new QueryWrapper<T>().select("DISTINCT " + filedName));
    }

}
